package h.d.bluetooth.visitor;

import h.d.bluetooth.visitor.common.BluetoothHandler;
import h.d.bluetooth.visitor.common.VaE;
import h.d.bluetooth.visitor.sort.SortData;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Message;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author hdeom
 * @date 2014. 1. 15.
 *
 */
public class BluetoothReceiver extends BroadcastReceiver{
	public static final String TAG = "BluetoothReceiver";
	/**
	 * @author hdeom
	 * @date 2014. 1. 15.
	 * @param
	 * @return
	 *
	 **/
	@Override
	public void onReceive(Context context, Intent intent) {

		String action = intent.getAction();
		Message msg = Message.obtain();
		Bundle b = new Bundle();

		// When discovery finds a device
		if (BluetoothDevice.ACTION_FOUND.equals(action)) {
			// Get the BluetoothDevice object from the Intent
			BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,  Short.MIN_VALUE);

			b.putParcelable("found_device", (Parcelable)new SortData("", "", device.getName(), device.getAddress(), rssi));
			msg.setData(b);
			msg.what = VaE.ADD_BLUETOOTH_DEVICE;
			BluetoothHandler.sendMessage(msg);

		} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {


			msg.what = VaE.FINISHI_BLUETOOTH_SCAN;
			BluetoothHandler.sendMessage(msg);
			/*if (mNewDevicesArrayAdapter.getCount() == 0) {
                String noDevices = getResources().getText(R.string.none_found).toString();
                mNewDevicesArrayAdapter.add(noDevices);
            }*/
		} else if(TextUtils.equals(Intent.ACTION_BATTERY_CHANGED, action)){
			if(VaE.HD) Log.d(TAG, "battery changed");
			int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
			String low_battery = App.getPreferenceValue(App.LOW_BETTERY, "y");
			String low_battery_value = App.getPreferenceValue(App.LOW_BETTERY_VALUE, "30");
			if(TextUtils.equals(low_battery, "y")){
				if(level < Integer.parseInt(low_battery_value)){
					msg.what = VaE.STOP_BLUETOOTH_SCAN;
					BluetoothHandler.sendMessage(msg);
				}
			}

		}
	}
}
